<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 聊天</title>
</head>
<body>
<h1>WebSocket 聊天</h1>

<div>
    <label for="username">用户名:</label>
    <input type="text" id="username" placeholder="请输入用户名">
    <button onclick="connect()">连接</button>
</div>

<div>
    <input type="text" id="receiver" placeholder="请输入接收人">
    <label for="messageInput">消息:</label>
    <input type="text" id="messageInput" placeholder="请输入消息">
    <button onclick="sendMessage()">发送</button>
</div>

<div id="messages"></div>

<script>
    let websocket;

    function connect() {
        const username = document.getElementById('username').value;
        if (!username) {
            alert('请输入用户名');
            return;
        }

        websocket = new WebSocket('ws://localhost:8080/chat?user=' + username);

        websocket.onopen = function(event) {
            console.log('连接已建立');
            document.getElementById('messages').innerHTML += '<p>连接已建立</p>';
        };

        websocket.onmessage = function(event) {
            const data = JSON.parse(event.data);
            console.log("--------------")
            console.log(data)
            console.log(event.data)
            document.getElementById('messages').innerHTML += `<p>${data.sender}: ${data.message}</p>`;
        };

        websocket.onclose = function(event) {
            console.log('连接已关闭');
            document.getElementById('messages').innerHTML += '<p>连接已关闭</p>';
        };

        websocket.onerror = function(error) {
            console.error('WebSocket 错误:', error);
            document.getElementById('messages').innerHTML += '<p>WebSocket 错误</p>';
        };
    }

    function sendMessage() {
        if (!websocket) {
            alert('请先连接到服务器');
            return;
        }

       var isPrivate= document.getElementById('receiver').value?true:false

        const messageInput = document.getElementById('messageInput');
        const message = messageInput.value;

        if (!message) {
            alert('请输入消息');
            return;
        }

        const messageObj = {
            'sender': document.getElementById('username').value,
            'message': message,
            'receiver':document.getElementById('receiver').value,
            'isPrivate': isPrivate
        };
        console.log('=======')
        console.log(messageObj)
        websocket.send(JSON.stringify(messageObj));
        messageInput.value = '';
    }
</script>
</body>
</html>